from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.mime.image import MIMEImage
import smtplib


class SendEmail(object):
    def __init__(self, mail_host, mail_user, mail_pass, sender):
        self.mailHost = mail_host
        self.mailUser = mail_user
        self.mailPass = mail_pass
        self.senderEmail = sender

    def sendEmailOk(self, to_addr, content):
        # 三个参数：第一个为文本内容，第二个 plain 设置文本格式，第三个 utf-8 设置编码
        message = MIMEText(content, 'plain', 'utf-8')
        message['From']    = self.senderEmail
        message['Subject'] = Header(content)
        to_addr = [to_addr]
        try:
            smtpObj = smtplib.SMTP_SSL(self.mailHost, port=465)
            smtpObj.login(self.mailUser, self.mailPass)
            smtpObj.sendmail(self.senderEmail, to_addr, message.as_string())
            print('通知邮件发送成功！')
        except smtplib.SMTPException as e:
            print(e)
            print('通知发送邮件失败！')

    # 发送二维码
    def sendEmailQrCode(self, receiverEmail):
        self.receiverEmail = receiverEmail
        msg = MIMEMultipart()
        msg.attach(MIMEText('请查收附件中的二维码图片。请打开12306APP扫描二维码进行登录。', 'plain', 'utf-8'))
        msg['From'] = self.senderEmail
        msg['To']   = receiverEmail
        msg['Subject'] = '二维码图片'

        # 添加二维码图片附件
        with open('qr_code.png', 'rb') as f:
            img = MIMEImage(f.read())
            img.add_header('Content-Disposition', 'attachment', filename='qr_code.png')
            msg.attach(img)
        # 发送邮件
        print(self.senderEmail, receiverEmail, msg.as_string())
        try:
            smtpObj = smtplib.SMTP_SSL(self.mailHost, port=465)
            smtpObj.login(self.mailUser, self.mailPass)
            print(self.senderEmail,receiverEmail)
            smtpObj.sendmail(self.senderEmail, [self.senderEmail,receiverEmail], msg.as_string())
            print('二维码邮件发送成功！')
            return True
        except Exception as e:
            print(f'二维码邮件发送失败: {e}')
            return False
    def sendSearchMessage(self, to_addr, content):
        message = MIMEText(content, 'plain', 'utf-8')
        message['From']    = self.senderEmail
        message['Subject'] = Header(content)
        to_addr = [to_addr, self.senderEmail]
        try:
            smtpObj = smtplib.SMTP_SSL(self.mailHost, port=465)
            smtpObj.login(self.mailUser, self.mailPass)
            smtpObj.sendmail(self.senderEmail, to_addr, message.as_string())
            print('通知邮件发送成功！')
        except smtplib.SMTPException as e:
            print(e)
            print('通知发送邮件失败！')